<template>
  <div class="user-list">
    <div class="user-list-title">{{title}}</div>
    <div class="user-list-container">
      <div class="ulist-function">
        <div class="ulist-search">
          <a-input :placeholder="placeholder"
                   v-model="userSearch"
                   class="ulist-input-search" />
          <a-button type="primary"
                    @click="handleSearch">
            查询
          </a-button>
          <a-button type="primary"
                    class="purple-button"
                    @click="openAdd">
            新增
          </a-button>
        </div>
        <div class="ulist-amount">{{amountStr}}:{{amount}}</div>
      </div>
      <div class="ulist-table-container">
        <a-table :columns="columns"
                 :row-key="record => record.id"
                 :data-source="data"
                 :loading="loading"
                 :pagination="false"
                 @change="handleTableChange">
          <template slot="lastModifiedDate"
                    slot-scope="text, record">
            <span>{{new Date(record.lastModifiedDate).toLocaleString()}}</span>
          </template>
          <template slot="operation"
                    slot-scope="text, record">
            <span class="user-operation"
                  @click="handleEdit(text, record)">编辑</span>
            <span class="user-operation"
                  @click="handlePswSet(text, record)">重置密码</span>
            <a-popconfirm title="确认删除？"
                          ok-text="是"
                          cancel-text="否"
                          @confirm="handleDelete(text, record)">
              <span class="user-operation">删除</span>
            </a-popconfirm>

          </template>
        </a-table>
      </div>
    </div>
    <div>
      <a-modal v-model="addVisible"
               title="新增用户"
               :footer="null">
        <a-form-model layout="horizontal"
                      :model="addForm"
                      @submit="handleAdd">
          <a-form-model-item>
            <a-input v-model="addForm.login"
                     placeholder="Username">
              <a-icon slot="prefix"
                      type="user"
                      style="color:rgba(0,0,0,.25)" />
            </a-input>
          </a-form-model-item>
          <a-form-model-item>
            <a-input v-model="addForm.password"
                     type="password"
                     placeholder="Password">
              <a-icon slot="prefix"
                      type="lock"
                      style="color:rgba(0,0,0,.25)" />
            </a-input>
          </a-form-model-item>
          <a-form-model-item>
            <a-input v-model="addForm.email"
                     placeholder="email">
              <!--              <a-icon slot="prefix" type="user" style="color:rgba(0,0,0,.25)" />-->
            </a-input>
          </a-form-model-item>
          <a-form-model-item>
            <a-radio-group v-model="addForm.role">
              <!--              <a-radio value="ROLE_ADMIN">-->
              <!--                管理员-->
              <!--              </a-radio>-->
              <a-radio value="ROLE_STUDENT">
                学生
              </a-radio>
              <a-radio value="ROLE_TEACHER">
                老师
              </a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item>
            <a-button type="primary"
                      html-type="submit">
              新增用户
            </a-button>
          </a-form-model-item>
        </a-form-model>
      </a-modal>
      <a-modal v-model="editVisible"
               title="编辑用户"
               :footer="null">
        <a-form-model ref="editForm"
                      layout="horizontal"
                      :model="editModal"
                      :rules="editRules"
                      @submit="onEdit">
          <a-form-model-item prop="login">
            <a-input v-model="editModal.login"
                     placeholder="请修改用户名">
              <a-icon slot="prefix"
                      type="user"
                      style="color:rgba(0,0,0,.25)" />
            </a-input>
          </a-form-model-item>
          <a-form-model-item prop="email">
            <a-input v-model="editModal.email"
                     placeholder="请修改邮箱">
              <a-icon slot="prefix"
                      type="mail"
                      style="color:rgba(0,0,0,.25)" />
            </a-input>
          </a-form-model-item>
          <a-form-model-item>
            <a-button type="primary"
                      html-type="submit">
              编辑用户
            </a-button>
          </a-form-model-item>
        </a-form-model>
      </a-modal>
      <a-modal v-model="setPswVisible"
               title="重置用户密码"
               :footer="null">
        <a-form-model ref="setPswForm"
                      :model="setPswModal"
                      :rules="setPswRules"
                      @submit="onsetPsw">
          <a-form-model-item prop="psw"
                             has-feedback>
            <a-input v-model="setPswModal.psw"
                     type="password"
                     placeholder="请输入新密码">
              <a-icon slot="prefix"
                      type="lock"
                      style="color:rgba(0,0,0,.25)" />
            </a-input>
          </a-form-model-item>
          <a-form-model-item prop="pswconfirm"
                             has-feedback>
            <a-input v-model="setPswModal.pswconfirm"
                     type="password"
                     placeholder="请确认密码">
              <a-icon slot="prefix"
                      type="lock"
                      style="color:rgba(0,0,0,.25)" />
            </a-input>
          </a-form-model-item>
          <a-form-model-item>
            <a-button type="primary"
                      html-type="submit">
              重置密码
            </a-button>
          </a-form-model-item>
        </a-form-model>
      </a-modal>
    </div>
  </div>

</template>

<script>
  /* eslint-disable */
  import api from "../../common/api"

  const columns = [
    {
      title: '姓名',
      dataIndex: 'login',
      sorter: true,
      width: '20%',
      scopedSlots: { customRender: 'login' },
    },
    {
      title: '邮箱',
      dataIndex: 'email',
    },
    {
      title: '最近修改时间',
      dataIndex: 'lastModifiedDate',
      scopedSlots: { customRender: 'lastModifiedDate' },

    },
    {
      title: '操作',
      dataIndex: 'operation',
      scopedSlots: { customRender: 'operation' },
    },
  ];

  export default {
    props: {
      role: {
        type: String,
        default: "ROLE_TEACHER"
        //ROLE_STUDENT
      }
    },
    data () {

      let validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入新密码'));
        } else {
          if (this.setPswModal.pswconfirm !== '') {
            this.$refs.setPswForm.validateField('pswconfirm');
          }
          callback();
        }
      };
      let validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入新密码'));
        } else if (value !== this.setPswModal.psw) {
          callback(new Error("两次输入不一致"));
        } else {
          callback();
        }
      };

      return {
        data: [],
        pagination: {},
        loading: false,
        columns,
        userSearch: "",
        addVisible: false,
        editVisible: false,
        setPswVisible: false,
        deleteVisible: false,
        userId: "",
        editModal: {
          login: "",
          email: "",
        },
        editRules: {
          login: [
            {
              required: true,
              message: " ",
              // trigger: "blur",
              whitespace: true
            },
          ],
          email: [
            {
              required: true,
              message: " ",
              // trigger: "blur",
              whitespace: true
            },
          ],
          password: [
            {
              required: true,
              message: " ",
              trigger: "blur",
              whitespace: true
            },
          ],
        },
        setPswModal: {
          psw: "",
          pswconfirm: ""
        },
        setPswRules: {
          psw: [{ validator: validatePass, trigger: 'change' }],
          pswconfirm: [{ validator: validatePass2, trigger: 'change' }],
        },
        title: "教师管理",
        placeholder: "教师姓名",
        amountStr: "教师人数",
        amount: 999,
        addForm: {
          email: '',
          login: '',//用户名
          password: '',
          role: this.role,//用户角色，分为ROLE_ADMIN, ROLE_STUDENT, ROLE_TEACHER
        }
      };
    },
    mounted () {
      this.getUserList("mounted")
      // this.$nextTick(() => {this.getUserList("mounted")})
      setTimeout(() => {
        this.getUserList("mounted")
      }, 400)
    },
    methods: {
      getUserList (from = '') {
        // console.log("getUserList",from,this.role)
        this.userSearch = ''
        this.loading = true;
        this.$getCPG(api.getUserList, { role: this.role, size: 1000 }).then((res) => {
          // console.log("res: " + res);
          const pagination = { ...this.pagination };
          pagination.total = res.data.length;
          this.loading = false;
          this.data = res.data;
          this.pagination = pagination;
          this.amount = res.data.length;
        })
      },
      handleSearch () {
        // console.log(this.userSearch)
        this.loading = true;
        this.$getCPG(api.getUserList, { keyword: this.userSearch, role: this.role }).then((res) => {
          // console.log("res: " + res);
          const pagination = { ...this.pagination };
          pagination.total = res.data.length;
          this.loading = false;
          this.data = res.data;
          this.pagination = pagination;
          this.amount = res.data.length;
        })

      },
      handleAdd (e) {
        // console.log(this.addForm)
        this.$postCPG(api.register, {
          email: this.addForm.email,
          login: this.addForm.login,
          password: this.addForm.password,
          role: this.addForm.role,
        }).then((res) => {
          // console.log(res)
          this.$message.success('成功添加用户');
          this.addForm = {
            email: '',
            login: '',//用户名
            password: '',
            role: '',//用户角色，分为ROLE_ADMIN, ROLE_STUDENT, ROLE_TEACHER
          }
          this.addVisible = false
          this.getUserList('add')
        }).catch(err => {
          console.log(err)
          this.addVisible = false
        })
      },
      openAdd () {
        this.addVisible = true
        this.addForm.role = this.role
        // console.log(this.role)
      },
      handleEdit (text, record) {
        this.userId = record.id;
        this.editModal.login = record.login
        this.editModal.email = record.email
        this.editVisible = true;
        // console.log("edit " + text, record);
      },
      onEdit () {
        console.log("onedit")
        this.$refs.editForm.validate((valid) => {
          console.log("3587",valid)
          if (valid) {
            this.$putCPG(api.updateUserInfo, {
              ...this.editModal,
              id: this.userId,
            }).then((res) => {
              console.log("res", res)
              if (res.success) {
                this.$message.success('成功编辑用户');
                this.editVisible = false;
                this.getUserList()
              }
            })
          }else{
            console.log("!validate")
          }
        });
      },

      handlePswSet (text, record) {
        this.userId = record.id;
        this.setPswVisible = true;
      },
      onsetPsw () {
        this.$refs.setPswForm.validate((valid) => {
          this.$putCPG(api.updateUserInfo, {
            password: this.setPswModal.psw,
            id: this.userId
          }).then((res) => {
            if (res.success) {
              this.$message.success('成功重置密码');
              this.setPswVisible = false;
              this.getUserList()
            }
          })
        })
      },
      handleDelete (text, record) {
        console.log("delete " + record.login);
        this.$deletefnCPG(
          api.delUser,
          { login: record.login }
        ).then(res => {

          if (res.success) {
            this.$message.success('成功删除');
            this.getUserList('del')
          } else {
            this.$message.error('删除失败');
          }
        }).catch(err => {
          console.log(err)
        })
      },
      handleTableChange (pagination, filters, sorter) {
        const pager = { ...this.pagination };
        pager.current = pagination.current;
        this.pagination = pager;
        this.fetch({
          results: pagination.pageSize,
          page: pagination.current,
          sortField: sorter.field,
          sortOrder: sorter.order,
          ...filters,
        });
      },
    },
    watch: {
      //tab切换
      role: {
        immediate: true,
        handler (val) {
          // console.log("watch", val)
          if (val === 'ROLE_TEACHER') {
            this.title = "教师管理",
              this.placeholder = "教师姓名",
              this.amountStr = "教师人数"
          } else {
            this.title = "学生管理",
              this.placeholder = "学生姓名",
              this.amountStr = "学生人数"
          }
          this.getUserList('tabchange')
        }
      }
    }
  };
</script>

<style scoped lang="less">
  .user-list {
  .user-list-title {
    margin: 20px 0;
    height: 25px;
    font-size: 18px;
    font-family: PingFang SC, sans-serif;
    font-weight: bold;
    line-height: 25px;
    color: #242425;
  }
  .user-list-container {
    background-color: #fff;
  .ulist-function {
    height: 70px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 23px;
  .ulist-search {
    display: flex;
    justify-content: center;
  /deep/ input {
    border-radius: 15px;
    height: 30px;
    width: 125px;
  }
  /deep/ button {
    width: 120px;
    height: 30px;
    margin-left: 20px;
  }
  }
  .ulist-amount {
    height: 20px;
    font-size: 14px;
    font-family: PingFang SC, sans-serif;
    font-weight: 400;
    line-height: 20px;
    color: #1bd0a2;
  }
  }
  .ulist-table-container {
  /deep/.user-operation {
    margin-right: 20px;
    color: #41d8b1;
    cursor: pointer;
  }
  }
  .user-pagination {
    margin-top: 20px;
    text-align: right;
    padding-bottom: 20px;
  }
  }
  }
</style>
